package com.ash.controller;


import com.ash.util.CodeUtils;

import com.ash.util.TimeAndDataUtils;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author : Chen Chao
 * @description 验证码controller
 * @encoding : UTF-8
 * @date : 2022/2/7 20:30
 * @file : CodeController.java
 * @software : IntelliJ IDEA
 * @since : 1.8
 */
@RestController
@RequestMapping("/code_controller")
public class CodeController {
    @Resource
    private RedisTemplate redisTemplate;


    @RequestMapping("/test01")
    public String test01() {
        redisTemplate.opsForValue().set("name", "lucy");
        return String.valueOf(redisTemplate.opsForValue().get("name"));
    }

    @RequestMapping("/test02")
    public String test02(@RequestParam("iphoneNumber") String iphoneNumber) {

        if (StringUtil.isNullOrEmpty(iphoneNumber) || !CodeUtils.isMobile(iphoneNumber)) {
            return "手机号不正确";
        }
        /*生成验证码*/
        String checkCode = CodeUtils.createCheckCode();
        Object code = redisTemplate.opsForValue().get("check" + iphoneNumber + ":code");
        Object count = redisTemplate.opsForValue().get("check" + iphoneNumber + ":count");

        if (code != null) {
            return "发送请求过于繁忙，请稍后重试";
        }

        if (count == null) {
            /*第一次发送验证码的情况*/
            redisTemplate.opsForValue().set("check" + iphoneNumber + ":count", 1, TimeAndDataUtils.getRemainSecondsOneDay(new Date()), TimeUnit.SECONDS);
        } else if (Integer.parseInt(String.valueOf(count)) < CodeUtils.MAX_COUNT) {
            /*发送验证码小于等于3次*/
            redisTemplate.opsForValue().increment("check" + iphoneNumber + ":count", 1);
        } else {
            return "您今天已经达到最大请求次数：" + CodeUtils.MAX_COUNT + "次";
        }
        /*存储验证码*/
        redisTemplate.opsForValue().set("check" + iphoneNumber + ":code", checkCode, CodeUtils.TIME_OUT, TimeUnit.SECONDS);
        return "生成验证码成功，您的验证码为：" + checkCode;
    }

    @RequestMapping("/test03")
    public String test03(@RequestParam("checkCode") String checkCode, @RequestParam("iphoneNumber") String iphoneNumber) {
        if (StringUtil.isNullOrEmpty(iphoneNumber) || !CodeUtils.isMobile(iphoneNumber)) {
            return "手机号不正确";
        }
        if (StringUtil.isNullOrEmpty(checkCode)) {
            return "验证码不能为空";
        }
        Object o = redisTemplate.opsForValue().get("check" + iphoneNumber + ":code");
        if (!checkCode.equals(String.valueOf(o))) {
            System.out.println(o);
            return "验证码错误！";
        }
        return "验证码正确！";
    }
}
